using Microsoft.AspNetCore.Mvc;
using TestWebApi.IServices;
using TestWebApi.Models;
using TestWebApi.Util;

namespace TestWebApi.Controller;


[ApiController]
[Route("api/[controller]/[action]")]
public class UserController : ControllerBase
{
    private readonly JwtHelper _jwtHelper;
    private readonly IUserService _userService;
    private readonly IConfiguration _configuration;

    public UserController(IConfiguration configuration, IUserService userService)
    {
        _jwtHelper = new JwtHelper(configuration);
        _userService = userService;
        _configuration = configuration;
    }

    // 登录
    [HttpPost]
    public IActionResult Login(string email, string password,string connectionName="DefaultConnection")
    {
        var loginInfo = new LoginModel { Email = email, Pwd = password };
        // 检查连接名是否有效
        if (_configuration.GetConnectionString(connectionName) == null)
        {
            return BadRequest("无效的连接名");
        }
        if (!_userService.CheckUserPassword(loginInfo.Email, loginInfo.Pwd,connectionName))
        {
            return Unauthorized("密码错误");
        }

        var token = _userService.GetUserToken(loginInfo);
        return Ok(new { token });
    }

    // 注册
    [HttpPost]
    public IActionResult RegisterUser(string email, string password, RoleEnum role, string sex, int age,
        string userName, string connectionName="DefaultConnection")
    {
        // 检查连接名是否有效
        if (_configuration.GetConnectionString(connectionName) == null)
        {
            return BadRequest("无效的连接名");
        }
        if (!ModelState.IsValid) // 检查模型是否验证通过
        {
            return BadRequest(ModelState); // 返回错误信息
        }

        try
        {
            //检查用户是否已经注册
            if (_userService.UserExists(email, connectionName))
            {
         //       AppLogger.Warning("该邮箱已注册");
                return BadRequest("该邮箱已注册！");
            }

            var userModel = new UserModel(userName, role, email, password, age, sex);
            if (!_userService.CreateUser(userModel, connectionName))
                return BadRequest("注册失败");
         //   AppLogger.Information("用户创建成功: UserId = {UserId}, UserName = {UserName}, Email = {Email}", userModel.Id,
               // userModel.UserName, userModel.Email);
            return Ok("注册成功");
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
            throw;
        }
    }
}